<?php include('includes/array.in.php');?>
<div class="page">
	<div class="menu">
		<?php include('modules/members/dashboard.php');?>
    </div>
	<div class="products-list" style="overflow:hidden;">
    <?php
    	$sql = 'SELECT
					`units`.`name`
					, `stock`.*
				FROM
					`hkpacth_store`.`units`
					INNER JOIN `hkpacth_store`.`stock` 
						ON (`units`.`id` = `stock`.`unit`) 
				WHERE stock_date = "'.date('dmY',time()).'"';
		$q 	 = mysql_query($sql)or die(mysql_error());
		$c   = mysql_num_rows($q);
	?>    
    <h2>สต๊อกสินค้าวันที่ <span class="date" style="color:blue;"><?php echo ThaiTimeConvert(TIMESTAMP,0,0);?></span></h2>
      <table cellspacing="0" cellpadding="0" border="1">
        <thead>
	      <tr>
	        <td width="174" rowspan="2" align="center"><strong>รายการสินค้า</strong></td>
	        <td width="83" rowspan="2" align="center"><strong>ราคา/หน่วย</strong></td>
	        <td width="52" rowspan="2" align="center"><strong>หน่วย</strong></td>
	        <td width="69" rowspan="2" align="center"><strong>ยกมา</strong></td>
	        <td width="67" rowspan="2" align="center"><strong>รับ</strong></td>
	        <td width="58" rowspan="2" align="center"><strong>รวม</strong></td>
	        <td colspan="2" align="center"><strong>จ่าย</strong></td>
	        <td width="95" rowspan="2" align="center"><strong>จ่ายทั้งหมด</strong></td>
	        <td width="67" rowspan="2" align="center"><strong>คงเหลือ</strong></td>
	        <td width="74" rowspan="2" align="center"><strong>หมายเหตุ</strong></td>
        </tr>
	      <tr>
	        <td width="70" align="center"><strong>จ่ายลูกค้า</strong></td>
	        <td width="60" align="center"><strong>แถม</strong></td>
        </tr>
        </thead>
        <tbody>
        <?php if($c <= 0){ ?>
          <tr class="item-row">
	        <td align="center">
            	<div class="product-item">
                	<textarea class="product-name" style="height:16px;">ชื่อสินค้า</textarea>
                    <a title="Remove row" href="javascript:;" class="delete" stock_id="<?php echo $rs['stock_id'];?>">X</a>
               	</div>
            </td>
	        <td align="center">
            	<div class="unit_price">
            		
              	</div>
            </td>
	        <td align="center">
            	<div class="unit_name">
            		
                </div>
            </td>
	        <td align="center">
            	<div class="bring">
            		
              	</div>
            </td>
	        <td align="center">
            	<div class="product-reciev">
                	<textarea class="product-receive-num" field="receive" style="height:16px;width:60px;">0</textarea>                    
               	</div>
            </td>
	        <td align="center">
            	<div class="sum" field="sum">0</div>
            </td>
	        <td align="center">
            	<div class="product-pay-off">
                	<textarea class="product-pay-off-num" field="sale" style="height:16px;width:60px;">0</textarea>                    
               	</div>
            </td>
	        <td align="center">
            	<div class="product-bonus">
                	<textarea class="product-bonus-num" field="bonus" style="height:16px;width:50px;">0</textarea>                    
               	</div>
            </td>
	        <td align="center">
            	<div class="all_sale" field="all_sale">0</div>
            </td>
	        <td align="center">
            	<div class="total" field="total">0</div>
            </td>
	        <td align="center">
            	<div class="product-ann">
                	<textarea class="product-ann" field="annotation" style="height:16px;width:100px;"></textarea>                    
               	</div>
            </td>
          </tr>
		<?php }?>
        <?php while($rs	 = mysql_fetch_assoc($q)){?>
	      <tr class="item-row">
	        <td align="center">
            	<div class="product-item">
            		<?php echo $rs['product_name'];?>
                    <input type="hidden" class="delete" stock_id="<?php echo $rs['stock_id'];?>" value="<?php echo $rs['stock_id'];?>"/>		
                    <input type="hidden" class="product_name"  value="<?php echo $rs['product_name'];?>"/>         		
              	</div>
            </td>
	        <td align="center">
            	<div class="unit_price" data-price="<?php echo $rs['price'];?>">
            		<?php echo $rs['price'].'/'.$rs['name'];?>
              	</div>
            </td>
	        <td align="center">
            	<div class="unit_name">
            		<?php echo $rs['name'];?>
                </div>
            </td>
	        <td align="center">
            	<div class="bring">
            		<?php echo $rs['bring'];?>
              	</div>
            </td>
	        <td align="center">
            	<div class="product-receive">
                	<textarea class="product-receive-num" field="receive" style="height:16px;width:60px;"><?php echo $rs['receive'];?></textarea>                    
               	</div>
            </td>
	        <td align="center">
            	<div class="sum" field="sum"><?php echo $rs['sum'];?></div>
            </td>
	        <td align="center">
            	<div class="product-pay-off">
                	<textarea class="product-pay-off-num" field="sale" style="height:16px;width:60px;"><?php echo $rs['sale'];?></textarea>                    
               	</div>
            </td>
	        <td align="center">
            	<div class="product-bonus">
                	<textarea class="product-bonus-num" field="bonus" style="height:16px;width:50px;"><?php echo $rs['bonus'];?></textarea>                    
               	</div>
            </td>
	        <td align="center">
            	<div class="all_sale" field="all_sale"><?php echo $rs['all_sale'];?></div>
            </td>
	        <td align="center">
            	<div class="total" field="total"><?php echo $rs['total'];?></div>
            </td>
	        <td align="center">
            	<div class="product-ann">
                	<?php if($rs['annotation']!=""){
						echo '<img src="css/images/info.gif" title="'.$rs['annotation'].'">"';
					}else{
						echo '<textarea class="product-annotation" field="annotation" style="height:16px;width:50px;"></textarea>';
					}?>
                	
               	</div>
            </td>
          </tr>
          <?php } ?>
          <tr id="hiderow">
            <td colspan="11"><a title="Add a row" href="javascript:;" id="addrow">เพิ่มสินค้า</a></td>
          </tr>
        </tbody>
      </table>
      <h3 style="float:right;"><div>จำนวนเงินทั้งหมด <span class="sum_price" >00.00฿</span></div><div>ส่วนลดทั้งหมด <span class="sum_discount" >00.00฿</span></div><div>รวมเงินสุทธิ <span class="total_price" >00.00฿</span></div></h3>
	</div>
</div>
<script type="text/javascript">

function updateAllPrice(){
	var sumAllPrice = 0;
	var discount = 0;
	$('.all_sale').each(function(){
		sumAllPrice += (parseInt($(this).text()) * parseInt($(this).closest('tr').find('.unit_price').attr('data-price')));
		discount += (parseInt($(this).closest('tr').find('.product-bonus-num').val()) * parseInt($(this).closest('tr').find('.unit_price').attr('data-price')));
	});
	
	$('.sum_price').html(addCommas(roundNumber((sumAllPrice),2))+"฿");
	$('.sum_discount').html(addCommas(roundNumber((discount),2))+"฿");	
	$('.total_price').html(addCommas(roundNumber((sumAllPrice-discount),2))+"฿");
}

function updateSum(obj){
	var tr = obj.closest('tr');
	var stock_id = tr.find('.delete').attr('stock_id');
	var sum = parseInt(tr.find('.bring').text()) + parseInt($(this).val());
	tr.find('.sum').html(sum);
	updateTotal(obj)
	$.post('query.php',{update_sum_stock:true, stock_id:stock_id, receive:parseInt($(this).val()), sum:sum},function(result){},'html');
}

function updateAllSale(obj,txt){
	var tr = obj.closest('tr');
	var all_sale = parseInt(tr.find(txt).val()) + parseInt($(this).val());
	var sum = parseInt(tr.find('.sum').text());
	tr.find('.all_sale').html(all_sale);
	tr.find('.total').html(sum - all_sale);
	updateTotal(obj);
}

function updateTotal(obj){
	var tr = obj.closest('tr');
	var product_name = tr.find('.product_name').val();
	var stock_id = tr.find('.delete').attr('stock_id');
	var bring = $.trim(tr.find('.bring').text());
	var receive = tr.find('.product-receive-num').val();
	var sum = $.trim(tr.find('.sum').text());
	var sale= tr.find('.product-pay-off-num').val();
	var bonus = tr.find('.product-bonus-num').val();
	var sale_all = $.trim(tr.find('.all_sale').text());
	var total = parseInt(tr.find('.sum').text()) - parseInt(tr.find('.all_sale').text());
	//alert("bring ="+bring+"\n receive ="+receive+"\n sum ="+sum+"\n sale ="+sale+"\n bonus ="+bonus+"\n sale_all ="+sale_all+"\n total="+total);
	if(total >= 0){
		tr.find('.total').html(total);
		$.ajax({
			type	: 'POST',
			url		: 'query.php',
			data	: {	update_stock:true, 
						pname: product_name,
						stock_id:stock_id, 
						bring:bring, 
						receive:receive, 
						sum:sum, 
						sale:sale, 
						bonus:bonus, 
						all_sale:sale_all, 
						total:total},
			dataType: 'html',
			success	: function(result){
				location.reload();
				//alert(result);
				//if(result.status == 0){
					//alert('ไม่สามารถอัพเดทรายการได้ กรุณาตรวจสอบวิธีการป้อนข้อมูลหรือคัวเลขให้ถูกต้องด้วยค่ะ');
				//}
			}
		});
	}else{
		alert('คุณไม่สามารถจ่ายให้ลูกค้าได้เกินกว่าจำนวนของที่มี');
		tr.find('.product-pay-off-num').text('0');
		tr.find('.product-pay-off-num').val(0);
		tr.find('.total').html('0');
		tr.find('.all_sale').html('0');
		tr.find('.total').html(tr.find('.sum').text());
	}
	
}

$(function(){
	
	$('textarea').keypress(function(e){			
        if (e.which == 13) {
            e.preventDefault();
			return false;
        }
    });

	
	$("#addrow").click(function(){
		$(".item-row:last").after('<tr class="item-row"><td align="center"><div class="product-item"><textarea class="product-name" style="height:16px;">ชื่อสินค้า</textarea><a title="Remove row" href="javascript:;" class="delete" product-code="">X</a></div></td><td align="center"></td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center"><div class="product-reciev"><textarea class="product-reciev-num" style="height:16px;width:60px;">0</textarea></div></td><td align="center">&nbsp;</td><td align="center"><div class="product-pay-off"><textarea class="product-pay-off-num" style="height:16px;width:60px;">0</textarea></div></td><td align="center"><div class="product-bonus"><textarea class="product-bonus-num" style="height:16px;width:50px;">0</textarea></div></td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center"><div class="product-ann"><textarea class="product-ann" style="height:16px;width:100px;"></textarea></div></td></tr>');
		if ($(".delete").length > 0) $(".delete").show();
	
		$('.product-name').bind('keydown.autocomplete',function(){ 
			$(this).autocomplete({
				source: "search.php?table=products",
				select: function( event, ui ) {
					var _this = $(this);
					if(ui.item.label != ""){
						$.ajax({
							type 	: 'POST',
							url		: 'query.php',
							data	: {search_stock_products:true, data:ui.item.label},
							dataType: 'text',
							success	: function(msg){
								location.reload();
							}
						});	
					}
				}
			});
		});
	});
	
	if ($(".delete").length < 2) $(".delete").hide();
	
	$(".delete").live('click',function(){		 
		$(this).parents('.item-row').remove();
		if ($(".delete").length < 2) $(".delete").hide();	
	  if(confirm('คุณแน่ใจหรือเปล่าว่าต้องการลบสินค้านี้ออกจากรายการ')){		  
		 _this = $(this);
		 $.ajax({
			type 	: 'POST',
			url		: 'query.php',
			data	: {delete_stock:true, sid:_this.attr('stock-id')},
			dataType: 'text',
			success	: function(msg){
				_this.parents('.item-row').remove();
			 	if ($(".delete").length < 2) $(".delete").hide();
			}
		});
	  }
	});
	
	$( ".product-name" ).bind('keydown.autocomplete',function(){
		$(this).autocomplete({
			source: "search.php?table=products",
			select: function( event, ui ) {
				if(ui.item.label != ""){
					$.ajax({
						type 	: 'POST',
						url		: 'query.php',
						data	: {search_stock_products:true, data:ui.item.label},
						dataType: 'text',
						success	: function(msg){							
							location.reload();							
						}
					});	
				}
			}
		});
	});
	
	$('textarea.product-receive-num').blur(function(){
		field 	= $(this).attr('field');
		value	= $(this).val();
		_this	= $(this);
		if(typeof field != "undefined" && field != "undefined"){			
			updateSum(_this);
		}
	});
	$('textarea.product-pay-off-num').blur(function(){
		field 	= $(this).attr('field');
		value	= $(this).val();
		_this	= $(this);
		if(typeof field != "undefined" && field != "undefined"){			
			updateAllSale(_this,'textarea.product-bonus-num');
		}
	});
	$('textarea.product-bonus-num').blur(function(){
		field 	= $(this).attr('field');
		value	= $(this).val();
		_this	= $(this);
		if(typeof field != "undefined" && field != "undefined"){			
			updateAllSale(_this,'textarea.product-pay-off-num');
		}
	});
	
	$('textarea.product-ann').blur(function(){
		$.post('query.php',{
			update_annotation:true, 
			value:$(this).val(), 
			stock_id:$(this).closest('tr').find('.delete').val()
			},
			function(result){},'html');
	});
	
	updateAllPrice();
	
});
</script>
<style type="text/css">
table {
    border-collapse: collapse;
}
tbody > tr {
	background-color: #fff;
}
.delete {
    background: none repeat scroll 0 0 #EEEEEE;
    border: 1px solid;
    color: #000000;
    display: block;
    font-family: Verdana;
    font-size: 12px;
    font-weight: bold;
    left: 217px;
	margin-top:-25px;
    padding: 0 3px;
    position: absolute;
    text-decoration: none;
}
.delete-wpr { position: relative; }
.delete:hover {
	background-color: #EEFF88;
}
.wrapper {
	max-width: 884px;
	min-height: 600px;
}
h3 div span {
	color:red;
	float:right;
	float:right;
	width:100px;
	text-align:right;
}
</style>